﻿using Furion.DatabaseAccessor;
using Microsoft.EntityFrameworkCore;
using Dm;
using BJYJ_Admin.Core.SystemEntities;
using System.Reflection;
using BJYJ_Admin.EntityFramework.Core.DbContexts;
using System.IO;
using System.Linq;
using System;
using Furion.FriendlyException;
using Furion.Logging;
namespace BJYJ_Admin.EntityFramework.Core;

[AppDbContext("Default", DbProvider.Dm)]
//[AppDbContext("DefaultSql", DbProvider.SqlServer)]
public class DefaultDbContext : AppDbContext<DefaultDbContext>
{
    public DefaultDbContext(DbContextOptions<DefaultDbContext> options) : base(options)
    {
    }
    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {

        try
        {
            // 动态加载BJYJ_Admin.Core.xml的 XML 文件
            var assembly = Assembly.GetExecutingAssembly();
            var xmlFile = "BJYJ_Admin.Core.xml";
            var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
            if (File.Exists(xmlPath))
            {
                // 调用 XmlCommentHelper 加载 XML
                XmlCommentHelper.LoadXmlComments(xmlPath);
            }
            // 加载实体所在的程序集
            var entityAssembly = Assembly.Load("BJYJ_Admin.Core");
            // 获取所有继承自 Entity<> 的实体类型
            var entityBaseType = typeof(Entity<>);
            var entityTypes = entityAssembly.GetTypes()
                .Where(t => t.IsClass
                    && !t.IsAbstract
                    && IsSubclassOfGenericType(t, entityBaseType))
                .ToList();

            foreach (var entityType in entityTypes)
            {
                modelBuilder.Entity(entityType, entity =>
                {
                    foreach (var property in entityType.GetProperties())
                    {
                        var comment = XmlCommentHelper.GetCommentForProperty(
                            entityType.FullName,
                            property.Name
                        );
                        if (!string.IsNullOrEmpty(comment))
                        {
                            //将注释添加到数据库字段列属性
                            entity.Property(property.Name).HasComment(comment);
                        }
                    }
                });
            }
        }
        catch (Exception ex)
        {
            Log.Error(ex.Message);
        }
    }
    public static bool IsSubclassOfGenericType(Type type, Type genericBaseType)
    {
        while (type != null && type != typeof(object))
        {
            var currentType = type.IsGenericType ? type.GetGenericTypeDefinition() : type;
            if (genericBaseType == currentType)
            {
                return true;
            }
            type = type.BaseType;
        }
        return false;
    }

}
